package com.xuyuan.concurrent.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class ResourcePool implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(ResourcePool.class);
    private final Semaphore semaphore;

    public ResourcePool(int permits) {
        this.semaphore = new Semaphore(permits); // 设置许可数量
    }

    public static void main(String[] args) {
        ResourcePool resourcePool = new ResourcePool(3);
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 100; i++) {
            executorService.submit(resourcePool::run);
        }
    }

    @Override
    public void run() {
        boolean acquire = false;
        try {
            acquire = semaphore.tryAcquire(1, 2000, TimeUnit.MILLISECONDS); // 获取许可
            if (acquire) {
                logger.info("Thread {} is using the resource", Thread.currentThread().getId());
                Thread.sleep(100000); // 模拟使用资源的耗时操作
            } else {
                logger.warn("Thread {} failed to acquire the resource", Thread.currentThread().getId());
            }
        } catch (InterruptedException e) {
            logger.error("Thread {} was interrupted", Thread.currentThread().getId(), e);
            Thread.currentThread().interrupt(); // 恢复中断状态
        } finally {
            if (acquire && semaphore.availablePermits() < 3) { // 确保只有在成功获取许可的情况下才释放许可
                semaphore.release();
            }
        }
    }
}
